import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Select, InputNumber, Popconfirm, Tooltip, Descriptions } from 'antd';
import { ExclamationCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getWorkerList, addWoker, updateWoker, downWorkerList, batchStatus, getWorkerListSum } from '@/services/human-resources/api';
import { PlusOutlined } from '@ant-design/icons';
import OptForm from './OptForm';
import { OptType, ServiceType } from '@/utils/constants';
import { MsgType, showMsg, isSupportSticky, isExits, getjobStatus, isNull } from '@/utils/utils';
import { history } from 'umi';
import { ProFormFieldSet } from '@ant-design/pro-form';
import PermissionControl from '@/components/PermissionControl';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';

const WorkerList: React.FC = () => {
  const columns: ProColumns<HUMANRESOURCESAPI.WorkerItem>[] = [
    {
      title: '姓名',
      dataIndex: 'worker_name',
      width: 90,
      fieldProps: {
        placeholder: '输入姓名',
      }
    },
    {
      title: '工号',
      dataIndex: 'worker_no',
      width: 60,
      fieldProps: {
        placeholder: '输入工号',
      }
    },
    {
      title: '身份证号',
      dataIndex: 'id_no',
      width: 130,
      fieldProps: {
        placeholder: '输入身份证号',
      }
    },
    {
      title: '星级评分',
      dataIndex: 'rank',
      valueType: 'select',
      width: 60,
      valueEnum: {
        3: '三星',
        4: '四星',
        5: '五星',
      },
    },
    {
      title: '服务方式',
      dataIndex: 'service_type',
      width: 70,
      search: false,
      render: (_, record) => {
        return ServiceType[record.service_type as string];
      },
    },
    {
      title: '在职状态',
      dataIndex: 'job_status',
      valueType: 'select',
      width: 60,
      valueEnum: {
        Y: '在职',
        N: '离职',
        W: '待岗',
      },
    },
    {
      title: '待缴介绍费',
      dataIndex: 'wait_recom_price',
      hideInTable: true,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ProFormFieldSet>
            <InputNumber precision={2} style={{ width: '100%' }} placeholder="最小值" />
            <span style={{ padding: '0 5px' }}>-</span>
            <InputNumber precision={2} style={{ width: '100%' }} placeholder="最大值" />
          </ProFormFieldSet>
        );
      },
    },
    {
      title: '服务单数',
      dataIndex: 'service_num',
      width: 70,
      align: 'right',
      search: false,
    },
    {
      title: '服务费总额',
      dataIndex: 'total_service_price',
      valueType: 'money',
      align: 'right',
      search: false,
      width: 90,
    },
    {
      title: '介绍费总额',
      dataIndex: 'total_recom_price',
      valueType: 'money',
      align: 'right',
      search: false,
      width: 90,
    },
    {
      title: '已缴介绍费',
      dataIndex: 'total_pay_price',
      valueType: 'money',
      align: 'right',
      width: 90,
      search: false,
    },
    {
      title: '待缴介绍费',
      dataIndex: 'wait_recom_price',
      valueType: 'money',
      align: 'right',
      search: false,
      width: 90,
    },
    {
      title: '操作',
      align: 'center',
      // fixed: 'right',
      // fixed: isSupportSticky() ? 'right' : '',
      width: 120,
      valueType: 'option',
      render: (_, record) => [
        <PermissionControl key="eidt" action_id="300300002">
          <a
            onClick={() => {
              setVisible(true);
              setCurrentRow(record);
              setOptType(OptType.EDIT);
            }}
          >
            编辑
          </a>
        </PermissionControl>,

        <PermissionControl key="record" action_id="300300003,300300004">
          <a
            onClick={() => {
              history.push({
                pathname: '/human-resources/worker/service-record',
                query: {
                  worker_id: record.worker_id as string,
                  worker_name: record.worker_name as string,
                  worker_no: record.worker_no as string,
                },
              });
              setCurrentRow(record);
            }}
          >
            服务记录
          </a>
        </PermissionControl>,
      ],
    },
  ];
  const actionRef = useRef<ActionType>();
  const [visible, setVisible] = useState<boolean>(false);
  const [optType, setOptType] = useState<string>(OptType.ADD);
  const [currentRow, setCurrentRow] = useState<HUMANRESOURCESAPI.WorkerItem>({});

  const [downloadFlag, setDownloadFlag] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色
  // 批量选择的状态
  const [status, setStatus] = useState<string>('Y');
  const[selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [totalObj, setTotalObj] = useState([]);

  const job_status = [
    {
      label: '在职',
      value: 'Y'
    },
    {
      label: '待岗',
      value: 'W'
    },
    {
      label: '离职',
      value: 'N'
    }
  ]

  const download = async() => {
    setLoading(true);
    await downWorkerList(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }

  /**
   * 添加/更新护工信息
   * @param fields
   * @returns
   */
  const handleAdd = async (fields: HUMANRESOURCESAPI.WorkerItem) => {
    try {
      if (optType === OptType.ADD) {
        await addWoker({ ...fields });
      } else {
        await updateWoker({ ...fields });
      }
      showMsg(optType === OptType.ADD ? '添加成功' : '修改成功', MsgType.SUCCESS);
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  };
  // 批量改状态
  const onBatchStatus = () => {
    batchStatus({ worker_ids: selectedRowKeys, job_status: status }).then(res => {
      showMsg(`已批量修改为“${getjobStatus[status]}”`, 'success');
      actionRef.current?.clearSelected?.();
      setSelectedRowKeys([]);
      actionRef?.current?.reload();
    }).catch = (error) => {
      showMsg(error?.data?.errmsg)
    }
  }

  const getTotal = async(params) => {
    if (isExits('300300013')) {
      await getWorkerListSum(params).then(res => {
        setTotalObj(res);
      }).catch(error => {
        showMsg(error?.data?.errmsg);
      })
    }
  }

  useEffect(() => {
    
  }, [])



  return (
    <PageContainer extra={[<BreadcrumbDept />]} className="human-res-container" breadcrumb={{}}>
      <ProTable<HUMANRESOURCESAPI.WorkerItem, HUMANRESOURCESAPI.WorkerItem & COMMON.PageParams>
        rowKey="worker_id"
        actionRef={actionRef}
        bordered
        request={async (params) => {
          console.log(params);
          const { wait_recom_price } = params;
          if (wait_recom_price) {
            if (wait_recom_price[0] && wait_recom_price[2]) {
              if (wait_recom_price[0] > wait_recom_price[2]) {
                showMsg('待缴介绍费最大值不能小于最小值', MsgType.INFO);
                return {
                  data: [],
                  success: true,
                  total: 0,
                };
              }
            }
            if (Number(wait_recom_price[0]) < 0) {
              showMsg('最小值不能小于0', MsgType.INFO);
              return;
            }

            if (Number(wait_recom_price[2]) < 0) {
              showMsg('最大值不能小于0', MsgType.INFO);
              return;
            }
          }

          try {
            if (wait_recom_price) {
              // @ts-ignore
              params.min_wait_recom_price = wait_recom_price[0];
              // @ts-ignore
              params.max_wait_recom_price = wait_recom_price[2];
              delete params.wait_recom_price;
            }
            for (const prop in params) {
              if (!params[prop]) {
                delete params[prop];
              }
            }
            setSearchParams(params);
            getTotal(params);
            const data = await getWorkerList(params);
            setDownloadFlag(data.record_list.length > 0);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num,
            };
          } catch (error) {
            setDownloadFlag(false);
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0,
            };
          }
        }}
        search={{
          span: 6,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [
              <PermissionControl key="search" action_id="300300000">
                <Button
                  onClick={() => {
                    formProps.form?.submit();
                  }}
                  type="primary"
                >
                  查询
                </Button>
              </PermissionControl>,

              <PermissionControl action_id="300300010">
                <Button key="export" type="primary" loading={loading} disabled={!downloadFlag} onClick={download}>导出报表</Button>
              </PermissionControl>
            ];
          },
        }}
        options={false}
        toolBarRender={() => <div>
            {
              isExits('300300013') &&
              <div>
                <Descriptions className='humanOrderTotal' size="small" column={4}>
                  <Descriptions.Item
                    label='总人数'
                  >
                    <span className="green bold">{totalObj.tota_worker_num}</span>
                  </Descriptions.Item>
                  <Descriptions.Item
                    label={
                      <Tooltip title="在职人数 = 全部人数 - 离职人数">
                        在职人数 <QuestionCircleOutlined />
                      </Tooltip>
                    }
                  >
                    <span className="green bold">{totalObj.tota_y_worker_num}</span>
                  </Descriptions.Item>
                  <Descriptions.Item
                    label='待岗人数'
                  >
                    <span className="org bold">{totalObj.tota_w_worker_num}</span>
                  </Descriptions.Item>
                  <Descriptions.Item
                    label='离职人数'
                  >
                    <span className="red bold">{totalObj.tota_n_worker_num}</span>
                  </Descriptions.Item>
                  <Descriptions.Item
                    label={
                      <Tooltip title="介绍费总额   = 已收取介绍费 + 待收取介绍费（预估）">
                        介绍费总额 (估) <QuestionCircleOutlined />
                      </Tooltip>
                    }
                  >
                    <span className="green bold">￥{totalObj.total_recom_price}</span>
                  </Descriptions.Item>
                  <Descriptions.Item
                    label='已收取介绍费'
                  >
                    <span className="org bold">￥{totalObj.total_pay_price}</span>
                  </Descriptions.Item>
                  <Descriptions.Item
                    label='待收取介绍费 (估)'
                  >
                    <span className="red bold">￥{totalObj.total_wait_price}</span>
                  </Descriptions.Item>
                </Descriptions>
                <div style={{ marginBottom: 8, height: '1px', borderTop: '1px solid rgba(0, 0, 0, 0.06)' }} />
              </div>
            }
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <PermissionControl action_id="300300001">
                <Button
                  onClick={() => {
                    setVisible(true);
                    setCurrentRow({});
                    setOptType(OptType.ADD);
                  }}
                  icon={<PlusOutlined />}
                  type="primary"
                >
                  新增
                </Button>
              </PermissionControl>
              {
                isExits('300300011') && (
                  <div style={{
                    border: '1px solid #D8D8D8', 
                    display: 'flex',
                    height: 28,
                    alignItems: 'center',
                    marginLeft: 10,
                    padding: '0 2px'}}>
    
                    <Select style={{width: '100px !important'}} className="stock-select" onChange={(value: string) => {
                        actionRef.current?.clearSelected?.();
                        setSelectedRowKeys([]);
                        setStatus(value);
                      }} dropdownMatchSelectWidth={false} defaultValue="Y">
                        <Select.Option value="Y">设置在职</Select.Option>
                        <Select.Option value="W">设置待岗</Select.Option>
                        <Select.Option value="N">设置离职</Select.Option>
                    </Select>
                    <Popconfirm
                      title={`将选中记录修改为“${getjobStatus[status]}”状态，是否确认？`}
                      onConfirm={onBatchStatus}
                      // onCancel={cancel}
                      okText="确认"
                      cancelText="再想想"
                    >
                      
                      <Button 
                        style={{marginLeft: 10, height: '24px'}}
                        type="primary"
                        disabled={isNull(selectedRowKeys)}
                      >
                        批量操作
                        <Tooltip
                          title={
                            <div style={{ display: 'flex', alignItems: 'inherit' }}>
                              <ExclamationCircleOutlined style={{ margin: '2px 4px' }} />
                              <div style={{ fontSize: 12 }}>
                                <div>在职状态，护工可正常登记服务单，</div>
                                <div>待岗和离职状态，无法登记服务单。</div>
                              </div>
                            </div>
                          }
                        >
                          <QuestionCircleOutlined style={{ marginLeft: 5 }} />
                        </Tooltip>
                      </Button>
                    </Popconfirm>
                  </div>)
              }
            </div>
          </div>
        }
        // toolbar={{
        //   menu: {
        //     items: [
        //       {
        //         key: 'add',
        //         label: (
        //           <PermissionControl action_id="300300001">
        //             <Button
        //               onClick={() => {
        //                 setVisible(true);
        //                 setCurrentRow({});
        //                 setOptType(OptType.ADD);
        //               }}
        //               icon={<PlusOutlined />}
        //               type="primary"
        //             >
        //               新增
        //             </Button>
        //           </PermissionControl>
        //         ),
        //       },
        //       {
        //         key: 'batch',
        //         label: isExits('300300011') && (
        //           <div style={{
        //             border: '1px solid #D8D8D8', 
        //             display: 'flex',
        //             height: 28,
        //             alignItems: 'center',
        //             marginLeft: 10,
        //             padding: '0 2px'}}>
    
        //             <Select style={{width: '100px !important'}} className="stock-select" onChange={(value: string) => {
        //                 actionRef.current?.clearSelected?.();
        //                 setSelectedRowKeys([]);
        //                 setStatus(value);
        //               }} dropdownMatchSelectWidth={false} defaultValue="Y">
        //                 <Select.Option value="Y">设置在职</Select.Option>
        //                 <Select.Option value="W">设置待岗</Select.Option>
        //                 <Select.Option value="N">设置离职</Select.Option>
        //             </Select>
        //             <Popconfirm
        //               title={`将选中记录修改为“${getjobStatus[status]}”状态，是否确认？`}
        //               onConfirm={onBatchStatus}
        //               // onCancel={cancel}
        //               okText="确认"
        //               cancelText="再想想"
        //             >
                      
        //               <Button 
        //                 style={{marginLeft: 10, height: '24px'}}
        //                 type="primary"
        //                 disabled={isNull(selectedRowKeys)}
        //               >
        //                 批量操作
        //                 <Tooltip
        //                   title={
        //                     <div style={{ display: 'flex', alignItems: 'inherit' }}>
        //                       <ExclamationCircleOutlined style={{ margin: '2px 4px' }} />
        //                       <div style={{ fontSize: 12 }}>
        //                         <div>在职状态，护工可正常登记服务单，</div>
        //                         <div>待岗和离职状态，无法登记服务单。</div>
        //                       </div>
        //                     </div>
        //                   }
        //                 >
        //                   <QuestionCircleOutlined style={{ marginLeft: 5 }} />
        //                 </Tooltip>
        //               </Button>
        //             </Popconfirm>
        //           </div>)
        //       }
        //     ],
        //   },
        // }}
        columns={columns}
        // scroll={{ x: 1200 }}
        pagination={{
          showQuickJumper: true,
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.worker_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.worker_id === clickRow ? 'tableRowClick' : ''
        }}
        rowSelection={{
          columnWidth: 30,
          onChange: (sel) => {
            setSelectedRowKeys(sel);
          },
          getCheckboxProps: (record) => {
            return {
              disabled: [status].includes(record.job_status as string)
            }
          }
        }}
      />

      {visible && (
        <OptForm
          actionRef={actionRef}
          record={currentRow}
          handleAdd={handleAdd}
          handleModalVisible={setVisible}
          optType={optType}
          visible={visible}
        />
      )}
    </PageContainer>
  );
};
export default WorkerList;
